import React, { Component } from "react";
import { Checkbox } from "antd";
export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [
        // {
        //   title: 'react搭建项目',
        //   checked: true
        // },
        // {
        //   title: 'axios传递数据',
        //   checked: true
        // },
        // {
        //   title: '组件传值',
        //   checked: true
        // },
      ]
    };
  }

  componentDidMount() {
    let tempList = JSON.parse(localStorage.getItem("todolist"));
    // 如果不为null
    if (tempList!=null){
      this.setState({
        list: tempList
      });
    }  
  }

  //存储
  saveMsg = () => {
    console.log("ref监听 " + this.refs.msg.value);
    let tempList = this.state.list;
    tempList.push({
      title: this.refs.msg.value,
      checked: false
    });
    this.refs.msg.value = "";
    this.setState({
      list: tempList
    });
    localStorage.setItem("todolist", JSON.stringify(tempList));
  };

  //删除
  delMsg = key => {
    let tempList = this.state.list;
    tempList.splice(key, 1);
    this.setState({
      list: tempList
    });
    localStorage.setItem("todolist", JSON.stringify(tempList));
  };

  //改变checkbox
  changeCheckbox = key => {
    let tempList = this.state.list;
    tempList[key].checked = !tempList[key].checked;
    this.setState({
      list: tempList
    });
    localStorage.setItem("todolist", JSON.stringify(tempList));
  };

  render() {
    return (
      <div>
        主页Home组件
        <br />
        <input type="text" ref="msg" onChange={this.changeMsg} />
        <button onClick={this.saveMsg}>储存</button>
        <hr />
        待办
        <ul>
          {this.state.list.map((value, key) => {
            if (!value.checked) {
              return (
                <li key={key}>
                  <input
                    type="checkbox"
                    checked={value.checked}
                    onChange={this.changeCheckbox.bind(this, key)}
                  />
                  {value.title}
                  <button onClick={this.delMsg.bind(this, key)}>删除</button>
                </li>
              );
            }
          })}
        </ul>
        已办
        <ul>
          {this.state.list.map((value, key) => {
            if (value.checked) {
              return (
                <li key={key}>
                  <input
                    type="checkbox"
                    checked={value.checked}
                    onChange={this.changeCheckbox.bind(this, key)}
                  />
                  {value.title}
                  <button onClick={this.delMsg.bind(this, key)}>删除</button>
                </li>
              );
            }
          })}
        </ul>
      </div>
    );
  }
}
